//
//  BanJiKaoQingNextView.m
//  SanYiTeaching
//
//  Created by 李文强 on 2019/4/16.
//  Copyright © 2019 SanYi. All rights reserved.
//

#import "BanJiKaoQingNextView.h"
#import "SYRequestAPI+Teach.h"
#import "CJYearMonthSelectedView.h"
#import "CHAlertView.h"
@implementation BanJiKaoQingNextView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (instancetype)initWithFrame:(CGRect)frame{
    if ([super initWithFrame:frame]) {
        [self initSubView];
    }
    return self;
}
- (void)initSubView{
    pageSize = 30;
    pageIndex = 1;
    beginDate = @"";
    endDate = @"";
    _dataArray = [NSMutableArray new];
    self.backgroundColor = MAINBACKCOLOR;
    [self addSubview:self.backButton];
    [_backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@10);
        make.top.equalTo(@10);
        make.height.equalTo(@24);
        make.width.equalTo(@60);
    }];
    [self addSubview:self.tableList];
    [_tableList mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.right.equalTo(@0);
        make.bottom.equalTo(@0);
        make.top.equalTo(@44);
    }];
    [self addSubview:self.titleLabel];
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mas_centerX);
        make.centerY.equalTo(self.backButton.mas_centerY);
        make.width.equalTo(@120);
        make.height.equalTo(@20);
    }];
    
    [_tableList headerRefreshBlock:^{
        self->pageIndex = 1;
        [self->_dataArray removeAllObjects];
        [self setKaiShiShiJian];
        [self setJieShuShiJian];
        [self->_tableList.mj_header beginRefreshing];
        [self getBanJiKaoQingDetailRequest];
    }];
    [_tableList fooderRefreshBlock:^{
        [self->_tableList.mj_footer beginRefreshing];
        [self getBanJiKaoQingDetailRequest];
    }];
    [self setKaiShiShiJian];
    [self setJieShuShiJian];
}
- (UILabel *)titleLabel{
    if (!_titleLabel) {
        UILabel *label = [[UILabel alloc]init];
        label.text = @"考勤详情";
        label.textAlignment = 1;
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = TITLECOLOR;
        _titleLabel = label;
    }
    return _titleLabel;
}
- (UITableView *)tableList{
    if (!_tableList) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 0) style:UITableViewStylePlain];
        tableView.delegate  =self;
        tableView.dataSource = self;
        tableView.backgroundColor = [UIColor clearColor];
        [tableView registerClass:[BanJiKaoQingNextViewCell class] forCellReuseIdentifier:@"BanJiKaoQingNextViewCell"];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _headerView = [[BanJiKaoQingNextHeaderView alloc]init];
        _headerView.frame = CGRectMake(0, 0,self.mainw, 121);
        [_headerView.leftButton addTarget:self action:@selector(beginDateClick) forControlEvents:UIControlEventTouchUpInside];
        [_headerView.rightButton addTarget:self action:@selector(endDateClick) forControlEvents:UIControlEventTouchUpInside];
        tableView.tableHeaderView = _headerView;
        _tableList = tableView;
    }
    return _tableList;
}
- (void)beginDateClick{
    //添加时间选择
    [self kaiShiRiQiSelected];
}
- (void)endDateClick{
    //添加时间选择
    [self jieShuRiQiSelected];
}
#pragma mark - 开始日期选择
- (void)kaiShiRiQiSelected{
    [CJYearMonthSelectedView showDatePickerWithTitle:@"选择月份" andTypeOfFrame:CGRectMake(APP_WIDTH-520,APP_HEIGHT/2-150, 300, 300) minDateStr:@"2000-01" resultBlock:^(NSString * _Nonnull selectValue) {
        if ([selectValue isEqualToString:@"全部"]) {
            [MBProgressHUD zr_showError:@"请选择日期"];
            return ;
        }
        if (selectValue.length>0) {
            NSArray *array = [selectValue componentsSeparatedByString:@"-"];
           // NSLog(@"输出日期 %@",selectValue);
            self->kaishiNum = [self valueNum:array];
            if (self->jisshuNum>0) {
                if (self->jisshuNum>self->kaishiNum) {
                    self->beginDate = selectValue;
                    self->_headerView.leftButton.bottomLabel.text = self->beginDate;
                    [self getBanJiKaoQingDetailRequest];
                }else{
                    [XSInfoView showInfo:@"结束日期不能早于开始日期" onSubView:self];
                }
            }else{
                self->beginDate = selectValue;
                self->_headerView.leftButton.bottomLabel.text = selectValue;
                [self getBanJiKaoQingDetailRequest];
            }
        }
    }];
}
- (int)valueNum:(NSArray *)array{
    NSString *num = [NSString stringWithFormat:@"%@%@",array[0],array[1]];
    int nu = [num intValue];
    return nu;
}
#pragma mark - 结束日期选择
- (void)jieShuRiQiSelected{
    [CJYearMonthSelectedView showDatePickerWithTitle:@"选择月份" andTypeOfFrame:CGRectMake(APP_WIDTH-520,APP_HEIGHT/2-150, 300, 300) minDateStr:@"2000-01" resultBlock:^(NSString * _Nonnull selectValue) {
        if ([selectValue isEqualToString:@"全部"]) {
            [MBProgressHUD zr_showError:@"请选择日期"];
            return ;
        }
        if (selectValue.length>0) {
            NSArray *array = [selectValue componentsSeparatedByString:@"-"];
           // NSLog(@"输出日期 %@",selectValue);
            self->jisshuNum = [self valueNum:array];
            if (self->kaishiNum >0) {
                //开始日期有值
                if (self->jisshuNum<self->kaishiNum) {
                    [XSInfoView showInfo:@"结束日期不能早于开始日期" onSubView:self];
                }else{
                    self->jisshuNum = [self valueNum:array];
                    self->endDate = selectValue;
                    self->_headerView.rightButton.bottomLabel.text = self->beginDate;
                    [self getBanJiKaoQingDetailRequest];
                }
            }else{
                self->jisshuNum = [self valueNum:array];
                self->endDate = selectValue;
                self->_headerView.rightButton.bottomLabel.text = selectValue;
                [self getBanJiKaoQingDetailRequest];
            }
        }
    }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BanJiKaoQingNextViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BanJiKaoQingNextViewCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[BanJiKaoQingNextViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BanJiKaoQingNextViewCell"];
    }
    BanJiKaoQingDetailKaoQingList *model = _dataArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.row%2 == 0) {
        cell.backgroundColor = [UIColor whiteColor];
    }else{
        cell.backgroundColor = [UIColorChange colorwithHexString:@"#F8F8F8"];
    }
    [cell reloadViewLayout];
    //添加查看方法
    cell.checkButton.tag = indexPath.row+100;
    [cell.checkButton addTarget:self action:@selector(checkReson:) forControlEvents:UIControlEventTouchUpInside];
    [cell reloadViewLayout:@[model.courseName,model.lessonTime,model.teacher,model.campus,model.attendDate,model.status,@""]];
    return cell;
}
- (void)checkReson:(UIButton *)sender{
    int tag = (int)sender.tag - 100;
    BanJiKaoQingDetailKaoQingList *model = _dataArray[tag];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"原因" message:model.leaveReason preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confir = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:confir];

    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:NO completion:nil];
    
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (!_titleView) {
        _titleView = [[SJXQHeaderTitleView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 44) andArray:@[@"课程名",@"课次",@"老师",@"地点",@"日期",@"状态",@"原因"]];
        _titleView.backgroundColor = CONTENTBACKCOLOR;
    }
    return _titleView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *mainView = [[UIView alloc]init];
    return mainView;
}
- (UIButton *)backButton{
    if (!_backButton) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@" 返回" forState:UIControlStateNormal];
        [button setTitleColor:[UIColorChange colorwithHexString:@"SELECTEDCOLOR"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"back_color"] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:12];
        [button setTitleColor:SELECTEDCOLOR forState:0];
        [button addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
        _backButton = button;
    }
    return _backButton;
}
- (void)back:(UIButton *)sender{
    [UIView animateWithDuration:0.5 animations:^{
        self.frame = CGRectMake(APP_WIDTH, 0, APP_WIDTH, APP_HEIGHT);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}
- (void)reloadData{
    _headerView.titleLabel.text = _mainModel.className;
    [_headerView setXueHaoLabelValue:_mainModel.schedule];
    [_headerView setKeChengLabelValue:_courseName];
    [_headerView setRenKeLaoShiLabelValue:_mainModel.headmaster];
    [_headerView setJiaoShiLabelValue:[NSString stringWithFormat:@"%@ %@",_mainModel.campusName,_mainModel.classroom]];
    [_headerView setShangKeShiJianLabelValue:_mainModel.openDate];
    [self getBanJiKaoQingDetailRequest];
}
#pragma mark - 班级考勤详情Rrequest
- (void)getBanJiKaoQingDetailRequest{
    NSDictionary *parama = @{@"classId":_mainModel.classId,
                             @"studentId":_studentModel.id,
                             @"beginDate":beginDate,
                             @"endDate":endDate,
                             @"pageIndex":[NSString stringWithFormat:@"%d",pageIndex],
                             @"pageSize":[NSString stringWithFormat:@"%d",pageSize]};
  //  NSLog(@"得到班级考勤详情数据上传的单数 %@",parama);
    [MBProgressHUD mj_showMessage:nil toView:self];
    [SYRequestAPI sy_getClassServiceClassAttendDetailList:parama success:^(id  _Nonnull responseObject) {
       // NSLog(@"得到班级考勤详情数据 %@",responseObject);
        NSArray *array = [responseObject objectForKey:@"data"];
        if (array.count>0) {
            self->pageIndex ++;
        }
        for (NSDictionary *dic in array) {
            BanJiKaoQingDetailKaoQingList *model = [BanJiKaoQingDetailKaoQingList yy_modelWithJSON:dic];
            [self->_dataArray addObject:model];
        }
        [self.tableList reloadData];
        [MBProgressHUD mj_hideHUDForView:self];
        [self->_tableList.mj_footer endRefreshing];
        [self->_tableList.mj_header endRefreshing];
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self];
        [self->_tableList.mj_footer endRefreshing];
        [self->_tableList.mj_header endRefreshing];
    }];
}
- (void)setKaiShiShiJian{
    self->_headerView.rightButton.bottomLabel.text = setDate()[0];
    endDate = setDate()[0];
    NSArray *array = [endDate componentsSeparatedByString:@"-"];
    self->jisshuNum = [self valueNum:array];
}
- (void)setJieShuShiJian{
    self->_headerView.leftButton.bottomLabel.text = setDate()[1];
    beginDate = setDate()[1];
    NSArray *array = [beginDate componentsSeparatedByString:@"-"];
    self->kaishiNum = [self valueNum:array];
}
NS_INLINE NSMutableArray *setDate(){
    NSMutableArray *data = [NSMutableArray new];
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
    NSString *dateStr = [formatter stringFromDate:currentDate];
    NSInteger lastIndex = 0;
    NSDate *newdate;
    [data addObject:dateStr];
    [lastMonthComps setMonth:lastIndex-1];
    newdate = [calendar dateByAddingComponents:lastMonthComps toDate:currentDate options:0];
    NSString *dateStrNext = [formatter stringFromDate:newdate];
    [data addObject:dateStrNext];
    return data;
}
@end
